const app = getApp()
const Api = app.Api
import dayjs from "dayjs";
import router from '../../utils/router'
import store from '../../utils/store'
import {
    LaneDetailEnum
} from '../../enum/laneStatus'

Page({
    data: {
        role: '',
        todayLoadingCount: '暂无数据',
        isNoData: false,
        tableHeadList: ['车道', '今日完成订单', '可装物料', '当前状态'],
        tableData: [],
        timer: null,
        total: 0,
        totalCount: '暂无数据',
        selectCompany: store.getItem("selectCompany") || {},
        todayCars: 0, // 当日车辆
        allCars: 0, // 所有车辆
    },

    async onLoad() {
        await this.getList()
    },

    justWriteProfile() {
        const phoneNumber = store.getItem("phoneNumber")
        if (phoneNumber) {
            wx.request({
                url: `https://mingduzscloud.com/api/app/userIsExist?phoneNumber=${phoneNumber}`, //仅为示例，并非真实的接口地址
                data: {

                },
                header: {
                    'content-type': 'application/json' // 默认值
                },
                success(res) {
                    if (res.data.data.exist_code === 0) {
                        router.push('profile')
                    } else if (res.data.data.exist_code === 1) {
                        if (store.getItem("selectCompany")) {
                            console.log('用户已经进行了项目现场的选择')
                        } else {
                            router.push('company')
                        }
                    }
                }
            })
        } else {
            router.push('login')
        }
    },

    // 获取车道监控列表
    async getList() {
        const factoryId = store.getItem('factoryId')
        try {
            const res = await app.clientPost(`${app.ClientApi.getLaneMonitorList}/factoryId/${factoryId}`, {}, {
                loading: false
            })
            const newlist = res.list.map(item => {
                let maters = item.materialId.map(mater => {
                    return mater.name
                })
                let materNames = maters.join(',')
                return {
                    id: item.id,
                    laneName: item.laneName,
                    laneStatus: item.laneStatus,
                    laneStatusText: LaneDetailEnum[item.laneStatus].title,
                    orderNumber: item.orderNumber,
                    materNames
                }
            })
            this.setData({
                tableData: newlist
            })
        } catch (e) {
            console.log('e', e)
        }
    },
    // 轮询车道监控列表
    async getLaneList() {
        clearInterval(this.data.timer)
        this.data.timer = setInterval(async () => {
            await this.getList()
        }, 10000)
    },

    // 获取当日已完成装量
    async getTodayLoadingCount() {
        const factoryId = store.getItem("factoryId")
        try {
            const res = await app.clientPost(`${app.ClientApi.getTodayLoadedData}/factoryId/${factoryId}`, {
                startTime: dayjs().format('YYYY-MM-DD') + " 00:00:00",
                endTime: dayjs().format('YYYY-MM-DD') + " 23:59:59"
            }, {
                loading: false
            })
             // 获取40kg规格的数量 每一项都是装了多少包
            //  const fourthNumArr = res.map(item => {
            //     if (item.materialName ==='40kg') {
            //         if (item.supplementNumber === undefined || item.supplementNumber === null) {
            //             item.supplementNumber = 0
            //         }
            //         return item.coordinateId + item.supplementNumber
            //     }
            // })
            // 获取50kg规格的数组 每一项都是装了多少包
            // const fivethNumArr = res.map(item => {
            //     if (!item.materialName || item.materialName && item.materialName !== '40kg') {
            //         if (item.supplementNumber === undefined || item.supplementNumber === null) {
            //             item.supplementNumber = 0
            //         }
            //         return item.coordinateId + item.supplementNumber
            //     }
            // })
            // 如果为空的话默认设为0
            // const fourthData = fourthNumArr.map(item => {
            //     if (item === undefined) {
            //         item = 0
            //     }
            //     return item
            // })
             // 如果为空的话默认设为0
            // const fivethData = fivethNumArr.map(item => {
            //     if (item === undefined) {
            //         item = 0
            //     }
            //     return item
            // })
            // const fourthNum = fourthData.reduce((total, current) => {
            //     return total + current
            // }, 0)
            // const fivethNum = fivethData.reduce((total, current) => {
            //     return total + current
            // }, 0)
            // const totalCount = fourthNum ? (fourthNum * 0.04 + fivethNum * 0.05).toFixed(2) : (fivethNum * 0.05).toFixed(2)
            // const sums = res.map(item => {
            //     if (item.supplementNumber === undefined) {
            //         item.supplementNumber = 0
            //     }
            //     return item.coordinateId + item.supplementNumber
            // })
            // const totalCount = sums.reduce((total, item) => {
            //     return total + item
            // }, 0) / 20
            this.setData({
                todayLoadingCount: res
            })
        } catch (e) {
            this.setData({
                todayLoadingCount: '暂无数据'
            })
        }

    },

    // 获取今日车辆次数
    async getTodayCars() {
        const factoryId = store.getItem("factoryId")
        try {
            const res = await app.clientPost(`${app.ClientApi.getAllCarList}/page-num/1/page-size/10/factoryId/${factoryId}`, {
                startTime: dayjs().format('YYYY-MM-DD') + " 00:00:00",
                endTime: dayjs().format('YYYY-MM-DD') + " 23:59:59"
            }, {
                loading: false
            })
            this.setData({
                todayCars: res.total
            })
        } catch (e) {
            this.setData({
                todayCars: '暂无数据'
            })
        }
    },
    // 获取总车辆次数
    async getAllCars() {
        const startTime = '2019-01-01'
        const factoryId = store.getItem("factoryId")
        try {
            const res = await app.clientPost(`${app.ClientApi.getAllCarList}/page-num/1/page-size/10/factoryId/${factoryId}`, {
                startTime: startTime + " 00:00:00",
                endTime: dayjs().format('YYYY-MM-DD') + " 23:59:59"
            }, {
                loading: true
            })
            this.setData({
                allCars: res.total
            })
        } catch (e) {
            this.setData({
                allCars: '暂无数据'
            })
        }
    },
    // 获取累计水泥吨数
    async getLoadingData() {
        const startTime = '2019-01-01'
        const endTime = dayjs().format('YYYY-MM-DD')
        const factoryId = store.getItem("factoryId")
        try {
            const res = await app.clientGet(`${app.ClientApi.getLoadingData}/${startTime}/${endTime}/factoryId/${factoryId}`, {}, {
                loading: false
            })
            // 获取40kg规格的数量 每一项都是装了多少包
            const fourthNumArr = res.map(item => {
                if (item.materialName ==='40kg') {
                    if (item.supplementNumber === undefined || item.supplementNumber === null) {
                        item.supplementNumber = 0
                    }
                    return item.coordinateId + item.supplementNumber
                }
            })
            // 获取50kg规格的数组 每一项都是装了多少包
            const fivethNumArr = res.map(item => {
                if (!item.materialName || item.materialName && item.materialName !== '40kg') {
                    if (item.supplementNumber === undefined || item.supplementNumber === null) {
                        item.supplementNumber = 0
                    }
                    return item.coordinateId + item.supplementNumber
                }
            })
            // 如果为空的话默认设为0
            const fourthData = fourthNumArr.map(item => {
                if (item === undefined) {
                    item = 0
                }
                return item
            })
             // 如果为空的话默认设为0
            const fivethData = fivethNumArr.map(item => {
                if (item === undefined) {
                    item = 0
                }
                return item
            })
            const fourthNum = fourthData.reduce((total, current) => {
                return total + current
            }, 0)
            const fivethNum = fivethData.reduce((total, current) => {
                return total + current
            }, 0)
            const totalCount = fourthNum ? (fourthNum * 0.04 + fivethNum * 0.05).toFixed(2) : (fivethNum * 0.05).toFixed(2)
            // const sums = res.map(item => {
            //     if (item.coordinateId) {
            //         if (item.supplementNumber === undefined) {
            //             item.supplementNumber = 0
            //         }
            //         return item.coordinateId + item.supplementNumber
            //     }
            //     if (item.packageCount) {
            //         if (item.supplementNumber === undefined) {
            //             item.supplementNumber = 0
            //         }
            //         return item.packageCount + item.supplementNumber
            //     }
            // })
            // const totalCount = sums.reduce((total, item) => {
            //     if (item === undefined) {
            //         item = 0
            //     }

            //     return total + item
            // }, 0) / 20
            this.setData({
                totalCount: totalCount
            })
        } catch (e) {
            this.setData({
                totalCount: '暂无数据'
            })
        }

    },

    // 点击切换按钮 跳转到公司列表页面
    handleSwitchClick() {
        router.push('company')
    },

    // 点击车道监控每一行数据 进入到车道详情
    handleRowClick(e) {
        router.push('lane-detail', {
            query: {
                laneId: e.currentTarget.dataset.row.id
            }
        })
    },

    // 点击跳转到车辆列表页面
    toCarListByToday() {
        if (this.data.role === '1') {
            router.push('carlist', {
                query: {
                    today: 'today'
                }
            })
        } else {
            return
        }
    },

    toOrderToday() {
        if (this.data.role === '1') {
            router.push('order-all', {
                query: {
                    today: 'today'
                }
            })
        } else {
            return
        }
    },

    toOrderAll() {
        if (this.data.role === '1') {
            router.push('order-all')
        } else {
            return
        }
    },

    // 点击跳转到车辆列表页面
    toCarListByTotal() {
        if (this.data.role === '1') {
          router.push('carlist')
        } else {
            return
        }
    },
 // 获取用户权限
 async getUserInfo(phoneNumber) {
    const res = await app.get(`${Api.getUserInfo}?phoneNumber=${phoneNumber}`)
    const role = res[0].jurisdiction
    this.setData({
        role
    })
},
    async onShow() {
        const phoneNumber = store.getItem('phoneNumber')
        this.justWriteProfile()
        if (store.getItem("companyList").length) {
            this.setData({
                selectCompany: store.getItem('selectCompany')
            })
            await this.getTodayCars()
            await this.getAllCars()
            await this.getLoadingData()
            await this.getTodayLoadingCount()
            await this.getList()
            await this.getLaneList()
            await this.getUserInfo(phoneNumber)
        }
    },

    // 监听页面隐藏的生命周期钩子
    onHide() {
        // 清楚计时器
        clearInterval(this.data.timer)
    }
})